#include "gun.h"
#include <QDebug>
Gun::Gun(Player* own)
{
    owner = own;

    clipSize = 20;
    recoilTime =120;
    reloadTime = 10*360;
    //reloadTime = 0;


    bullets.clear();

    clip = clipSize;
    recoil = 0;
    reload = 0;

    isRealoading = false;
}

void Gun::fire(qreal x, qreal y, qreal ang)
{
    if (owner != 0)
    {
        if (clip > 0)
        {
            if (recoil <= 0 && !isRealoading)
            {
                Bullet * bullet = new Bullet(QPointF(x,y), ang, owner);
                bullets.append(bullet);
                connect(bullet,SIGNAL(hitPolygon()),this,SLOT(onHitPolygon()));
                connect(bullet,SIGNAL(hitPlayer(Player*,Player*)),this, SLOT(onHitPlayer(Player*,Player*)));
                recoil = recoilTime;
                clip--;

                emit gunFired(bullet);
            }
        } else
        {
            if (!isRealoading)
            {
                startReloading();
            }
        }
    }
}

int Gun::getStatus()
{
    if (isRealoading)
    {
        return 1;
    }
    return 0;
}

int Gun::getClipSize()
{
    return clipSize;
}
int Gun::getClip()
{
    return clip;
}
int Gun::getReloadTime()
{
    return reloadTime;
}
int Gun::getReload()
{
    return reload;
}

void Gun::startReloading()
{
    reload = 0;
    isRealoading = true;
}

void Gun::finishReloading()
{
	reload = reloadTime;
	isRealoading = false;
	clip = clipSize;
}

void Gun::setGunAngle(qreal a)
{
    angle = a;
}

void Gun::resetGun()
{
	recoil = 0;
	if (isRealoading)
	{
		finishReloading();
	}
}

void Gun::firePressed()
{
    isFirePressed = true;
    fire(owner->pos().rx(), owner->pos().ry(), angle);
}
void Gun::fireReleased()
{
    isFirePressed = false;
}

void Gun::updateGun()
{
    if (recoil > 0)
    {
        recoil-=20;
    }
    if (isRealoading)
    {
        reload+=20;
        if (reload >= reloadTime)
        {
            isRealoading = false;
            clip = clipSize;
        }
    }
    if (isFirePressed)
    {
        fire(owner->pos().rx(), owner->pos().ry(), angle);
    }
}

QVector<Bullet*> Gun::getBullets()
{
    return bullets;
}

Player* Gun::getOwner()
{
    return owner;
}

void Gun::setOwner(Player* o)
{
    owner = o;
}

int Gun::getRecoil()
{
    return recoil;
}
int Gun::getRecoilTime()
{
    return recoilTime;
}

void Gun::onHitPlayer(Player* p1, Player* p2)
{
	qDebug() << "gun emit hit";
	emit hitPlayer(p1,p2);
}

void Gun::onHitPolygon()
{
    Bullet* b = static_cast<Bullet*>(sender());
    if (owner->getIsRemote()) qDebug() << "hit polygon";
    bullets.remove(bullets.indexOf(b));
}
